import 'dart:async';
import 'dart:convert';

import 'package:fluro/fluro.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_chip/bean/Token.dart';
import 'package:flutter_chip/config/Api.dart';
import 'package:flutter_chip/config/Http.dart';
import 'package:flutter_chip/config/Routers.dart';
import 'package:flutter_chip/utils/sp_utils.dart';
import 'package:flutter_chip/utils/toast_utils.dart';
import 'package:flutter_chip/widget/view_loading.dart';
import 'package:mobsms/mobsms.dart';

class RegisterPage extends StatefulWidget {
  final String phone;

  const RegisterPage({Key key, this.phone}) : super(key: key);

  @override
  _RegisterPageState createState() => _RegisterPageState();
}

class _RegisterPageState extends State<RegisterPage> {
  bool _loading = false;
  String _loadStr = "注册中...";
  final _formKey = GlobalKey<FormState>();
  var _phoneController = TextEditingController();
  var _verifyController = TextEditingController();
  var _invaCodeController = TextEditingController();
  String _phone, _password;
  bool _isShowPwd = false;

  //倒计时按钮
  Timer _countTimer;
  String _btnStr = '获取验证码';
  int _count = 60;

  @override
  void initState() {
    super.initState();
    if (null != widget.phone && widget.phone.isNotEmpty) {
      _phoneController.value = TextEditingValue(text: widget.phone);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        elevation: 1.0,
        backgroundColor: Theme.of(context).canvasColor,
        titleSpacing: 0.0,
        centerTitle: true,
        title: Text('注册', style: TextStyle(fontSize: 18)),
      ),
      body: ProgressDialog(
        loading: _loading,
        msg: _loadStr,
        child: Form(
          key: _formKey,
          child: ListView(
              padding: EdgeInsets.symmetric(horizontal: 22.0),
              children: <Widget>[
                SizedBox(height: 40),
                buildPhoneTextField(),
                SizedBox(height: 20),
                buildVerifyTextField(),
                SizedBox(height: 20),
                buildPasswordTextField(),
                SizedBox(height: 20),
                buildInvitationTextField(),
                SizedBox(height: 40),
                buildRegisterButton(context)
              ]),
        ),
      ),
    );
  }

  Widget buildPhoneTextField() {
    return TextFormField(
      // ignore: missing_return
      validator: (String value) {
        var emailReg = RegExp(
            r'^((13[0-9])|(14[0-9])|(15[0-9])|(16[0-9])|(17[0-9])|(18[0-9])|(19[0-9]))\d{8}$');
        if (!emailReg.hasMatch(value)) {
          return '请输入正确的手机号';
        }
      },
      onSaved: (String value) => _phone = value,
      keyboardType: TextInputType.phone,
      controller: _phoneController,
      decoration: InputDecoration(
        labelText: '手机号',
        hintText: '请输入手机号',
        contentPadding: EdgeInsets.all(10),
        prefixIcon: Icon(Icons.smartphone),
        border: OutlineInputBorder(
          borderSide: BorderSide(
            color: Theme.of(context).accentColor,
          ),
          borderRadius: BorderRadius.all(Radius.circular(24)),
        ),
      ),
    );
  }

  Widget buildVerifyTextField() {
    return TextField(
      keyboardType: TextInputType.number,
      controller: _verifyController,
      decoration: InputDecoration(
        labelText: '验证码',
        hintText: '请输入验证码',
        contentPadding: EdgeInsets.all(10),
        prefixIcon: Icon(Icons.lock),
        suffixIcon: FlatButton(
            onPressed: () {
              FocusScope.of(context).requestFocus(FocusNode());
              sendVerify();
            },
            child: Text(_btnStr,
                style: TextStyle(
                    color: _count == 60
                        ? Theme.of(context).accentColor
                        : Colors.black38))),
        border: OutlineInputBorder(
          borderSide: BorderSide(
            color: Theme.of(context).accentColor,
          ),
          borderRadius: BorderRadius.all(Radius.circular(24)),
        ),
      ),
    );
  }

  Widget buildPasswordTextField() {
    return TextFormField(
      // ignore: missing_return
      validator: (value) {
        var pwd = RegExp(r'^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,18}$');
        if (!pwd.hasMatch(value)) {
          return '请输入6~18位字母数字组合密码';
        }
      },
      onSaved: (String value) => _password = value,
      obscureText: _isShowPwd,
      decoration: InputDecoration(
        labelText: '密码',
        hintText: '6~18位字母数字组合密码',
        contentPadding: EdgeInsets.all(10),
        prefixIcon: Icon(Icons.lock),
        suffixIcon: IconButton(
            onPressed: () {
              setState(() {
                _isShowPwd = !_isShowPwd;
              });
            },
            icon: Icon(_isShowPwd ? Icons.visibility : Icons.visibility_off)),
        border: OutlineInputBorder(
          borderSide: BorderSide(
            color: Theme.of(context).accentColor,
          ),
          borderRadius: BorderRadius.all(Radius.circular(24)),
        ),
      ),
    );
  }

  ///邀请码输入框
  Widget buildInvitationTextField() {
    return TextField(
      controller: _invaCodeController,
      decoration: InputDecoration(
        labelText: '邀请码',
        hintText: '请输入4位字母数字组合的邀请码',
        contentPadding: EdgeInsets.all(10),
        prefixIcon: Icon(Icons.confirmation_number),
        border: OutlineInputBorder(
          borderSide: BorderSide(
            color: Theme.of(context).accentColor,
          ),
          borderRadius: BorderRadius.all(Radius.circular(24)),
        ),
      ),
    );
  }

  ///注册按钮
  Align buildRegisterButton(BuildContext context) {
    return Align(
      child: SizedBox(
        height: 45.0,
        width: MediaQuery.of(context).size.width,
        child: RaisedButton(
          child: Text(
            '注册',
            style: TextStyle(color: Colors.white, fontSize: 18),
          ),
          color: Theme.of(context).accentColor,
          onPressed: () {
            print("注册点击");
            if (_formKey.currentState.validate()) {
              _formKey.currentState.save();
              FocusScope.of(context).requestFocus(FocusNode());
              checkVerify();
            }
          },
          shape: StadiumBorder(
              side: BorderSide(color: Theme.of(context).accentColor)),
        ),
      ),
    );
  }

  ///倒计时按钮
  void countDownTimer() {
    if (_countTimer != null) {
      return;
    }
    _btnStr = '${_count--}s重新获取';
    _countTimer = Timer.periodic(Duration(seconds: 1), (timer) {
      print("$_count");
      setState(() {
        if (_count > 0) {
          _btnStr = '${_count--}s后重新获取';
        } else {
          _btnStr = '获取验证码';
          _count = 60;
          _countTimer.cancel();
          _countTimer = null;
        }
      });
    });
  }

  ///发送验证码
  void sendVerify() {
    if (_countTimer != null) {
      return;
    }
    _phone = _phoneController.text;
    if (_phone.isEmpty) {
      Toast.show("请填写正确的手机号");
      return;
    }
    setState(() {
      _loading = true;
      _loadStr = "发送中...";
    });
    Smssdk.getTextCode(_phoneController.text, "86", "", (dynamic ret, Map err) {
      setState(() {
        _loading = false;
      });
      if (null != err) {
        print("$err");
        Toast.show(err["msg"]);
      } else {
        Toast.show("验证码已发送");
        countDownTimer();
      }
    });
  }

  void checkVerify() {
    String verifyCode = _verifyController.text;
    if (verifyCode.isEmpty) {
      Toast.show("验证码不能为空");
      return;
    }
    print("校验验证码：$_phone $verifyCode");
    setState(() {
      _loading = true;
      _loadStr = "注册中...";
    });
    Smssdk.commitCode(_phone, "86", _verifyController.text,
        (dynamic ret, Map err) {
      if (null != err) {
        setState(() {
          _loading = false;
        });
        Toast.show(err["msg"]);
      } else {
        register();
      }
    });
  }

  void register() {
    print("开始注册");
    Map<String, String> params = Map();
    params["phone"] = _phone;
    params["password"] = _password;
    if (_invaCodeController.text.isNotEmpty) {
      params["inviCode"] = _invaCodeController.text;
    }
    Http.post(Api.LOGIN_REGIST, params: params, successCallBack: (data) {
      setState(() {
        _loading = false;
      });
      Token token = Token.fromJson(json.decode(data));
      if (null != token) {
        SpUtils.put(SpUtils.SP_TOKEN, token.token);
      }
      getUserInfo();
    }, errorCallBack: (msg) {
      setState(() {
        _loading = false;
      });
      Toast.show(msg);
    });
  }

  ///登录成功后获取用户信息
  void getUserInfo() {
    Http.get(Api.URL_INFO, successCallBack: (data) {
      setState(() {
        _loading = false;
      });
      Toast.show('注册成功');
      Routers.router.navigateTo(context, Routers.PAGE_MAIN,
          transition: TransitionType.inFromRight, clearStack: true);
    }, errorCallBack: (msg) {
      Toast.show(msg);
      setState(() {
        _loading = false;
      });
    });
  }

  @override
  void dispose() {
    super.dispose();
    if (null != _countTimer) {
      _countTimer.cancel();
      _countTimer = null;
    }
  }
}
